//
//  ZYDeviceCommonItemView.m
//  YiLin
//
//  Created by Zyark on 2018/6/4.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYDeviceCommonItemView.h"
//#import "ZYCircleSlider.h"
#import "ZYDevice.h"
#import "ZYModeSelectView.h"
#import "ZCircleSlider.h"
//#import "ZYCircleHanderView.h"

@interface ZYDeviceCommonItemView()<ZYModeSelectViewDelegate>

@property(nonatomic,strong) UIView *leftView;

@property(nonatomic,strong) UIView *middleView;

@property(nonatomic,strong) UIView *rightView;

@property(nonatomic,strong) UILabel *nameLabel;

/**
 模式图片
 */
@property(nonatomic,strong) UIImageView *modeImageView;

/**
 模式
 */
@property(nonatomic,strong) UILabel *modeLabel;

/**模式背景*/
@property(nonatomic,strong) UIView *modeBgView;

///**
// 可拖动圆形进度条
// */
//@property(nonatomic,strong) ZYCircleSlider *circleSilder;

/**
 wifi
 */
@property(nonatomic,strong) UIImageView *wifiImageView;

/**
 温度
 */
@property(nonatomic,strong) UILabel *temperatureLabel;

/**
 温度符号
 */
@property(nonatomic,strong) UILabel *temperatureSymbolLabel;

/**
 pm2.5
 */
@property(nonatomic,strong) UILabel *pmLabel;

/**
 TVOC
 */
@property(nonatomic,strong) UILabel *tvocLabel;

/**
 室温
 */
@property(nonatomic,strong) UILabel *roomTemperatureLabel;

/**
 湿度
 */
@property(nonatomic,strong) UILabel *humidityLabel;

/**
 模式选择
 */
@property(nonatomic,strong) ZYModeSelectView *modeSelectView;

/**
 是否弹出
 */
@property(nonatomic,assign) BOOL isAlterSelectView;

/**圆*/
@property(nonatomic,strong) ZCircleSlider *circleHanderView;

//@property(nonatomic,strong) ZYCircleHanderView *circleHanderView;

/**
 温度增加
 */
@property(nonatomic,strong) UIButton *addButton;

/**
 温度减少
 */
@property(nonatomic,strong) UIButton *reduceButton;
//    _circleHanderView.maxTempure = 31;
//    _circleHanderView.minTempure = 10;
/**最大温度*/
@property(nonatomic,assign) CGFloat maxTempure;

/**最小温度*/
@property(nonatomic,assign) CGFloat minTempure;
@end

@implementation ZYDeviceCommonItemView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

-(void)setup{
//    _leftView = [self setupSidesView];
//    _leftView.centerX = 0;
//    _leftView.top = 0;
//    
//    _rightView = [self setupSidesView];
//    _rightView.centerX = self.right;
//    _rightView.top = 0;
    
//    CGFloat width = ZYSCREEN_W * 0.65;
    _maxTempure = 31;
    _minTempure = 10;
    CGFloat width = ZYSCREEN_W;
    _middleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, self.height)];
    [_middleView setBackgroundColor:[UIColor clearColor]];
    _middleView.layer.cornerRadius = 5;
    _middleView.layer.masksToBounds = YES;
    [self addSubview:_middleView];
    _middleView.centerY = self.centerY;
    _middleView.centerX = self.centerX;
    
    /**wifi图片*/
    _wifiImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_home_main_wifi"]];
    [_middleView addSubview:_wifiImageView];
    _wifiImageView.left = 15;
    _wifiImageView.top = 10;
    
    /**设备名称*/
    _nameLabel = [[UILabel alloc] init];
    _nameLabel.size = CGSizeMake(30, 18);
    _nameLabel.textColor = kDeviceLabelColor;
    _nameLabel.font = [UIFont systemFontOfSize:16];
    [_middleView addSubview:_nameLabel];
    _nameLabel.centerY = _wifiImageView.centerY;
    _nameLabel.left = _wifiImageView.right + 3;
    
    if(ZYiPhone4_OR_4s || ZYiPhone5_OR_5c_OR_5s){
        _modeBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
    }else{
        _modeBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0.2 * self.width, 0.2 * self.width)];
    }
    _modeBgView.backgroundColor = [UIColor whiteColor];
    _modeBgView.layer.cornerRadius = 10;
    _modeBgView.layer.masksToBounds = YES;
    [_middleView addSubview:_modeBgView];
    _modeBgView.right = _middleView.width - 15;
    _modeBgView.top = 10;
    
    /**模式图片*/
    _modeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_home_mode_custom_selected"]];
    [_modeBgView addSubview:_modeImageView];
    _modeImageView.centerX = _modeBgView.width / 2;
    _modeImageView.top = 5;
    [_modeImageView setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSlectMode)];
    [_modeImageView addGestureRecognizer:tap];
    
    /**模式*/
    _modeLabel = [[UILabel alloc] init];
    _modeLabel.size = CGSizeMake(_modeBgView.width, 16);
    _modeLabel.textColor = kMainColor;
    _modeLabel.textAlignment = NSTextAlignmentCenter;
    _modeLabel.font = [UIFont systemFontOfSize:14];
    [_modeBgView addSubview:_modeLabel];
    _modeLabel.centerX = _modeImageView.centerX;
    _modeLabel.top = _modeImageView.bottom + 5;
    
    /**圆形进度条*/
    CGFloat circleSilderHeight = _middleView.height * 0.70;
    _circleHanderView = [[ZCircleSlider alloc] initWithFrame:CGRectMake(0, 0, circleSilderHeight, circleSilderHeight)];
    _circleHanderView.minimumTrackTintColor = kCircleSliderColor;
    _circleHanderView.maximumTrackTintColor = [UIColor whiteColor];
    _circleHanderView.backgroundTintColor = [UIColor whiteColor];
    _circleHanderView.circleBorderWidth = 10.0f;
    _circleHanderView.thumbRadius = 12.5;
    _circleHanderView.thumbExpandRadius = 14;
//    _circleHanderView.thumbTintColor = [UIColor redColor];
    _circleHanderView.circleRadius = circleSilderHeight / 2 - 9;
    _circleHanderView.value = 0;
    _circleHanderView.loadProgress = 0;
    [_circleHanderView addTarget:self
                      action:@selector(circleSliderTouchDown:)
            forControlEvents:UIControlEventTouchDown];
    [_circleHanderView addTarget:self
                      action:@selector(circleSliderValueChanging:)
            forControlEvents:UIControlEventValueChanged];
    [_circleHanderView addTarget:self
                      action:@selector(circleSliderValueDidChanged:)
            forControlEvents:UIControlEventTouchUpInside];
//    _circleHanderView = [[ZYCircleHanderView alloc] initWithFrame:CGRectMake(0, 0, 236, 236)];
//    [_circleHanderView setLineWidth:8];
//    _circleHanderView.maxTempure = 31;
//    _circleHanderView.minTempure = 10;
//    _circleHanderView.delegate = self;
    
    //    [_circleSilder setBackgroundColor:[UIColor whiteColor]];
    //    [_circleSilder setTintColor:kMainColor];
    [_middleView addSubview:_circleHanderView];
    _circleHanderView.centerX = _middleView.width / 2;
    if(ZYiPhone5_OR_5c_OR_5s || ZYiPhone4_OR_4s){
        _circleHanderView.top = _nameLabel.bottom ;
    }else{
        _circleHanderView.top = _nameLabel.bottom + 5;
    }
    
    //增加 减少 按钮
//    _addButton = [self setupButton:YES];
//    _reduceButton = [self setupButton:NO];
//    _addButton.centerX = _circleHanderView.left / 2;
//    _addButton.centerY = _circleHanderView.top + _circleHanderView.height * 0.3;
//
//    _reduceButton.centerX = _addButton.centerX;
//    _reduceButton.centerY = _circleHanderView.bottom - _circleHanderView.height * 0.3;
//
//    [_addButton addTarget:self action:@selector(temperatureAdd:) forControlEvents:UIControlEventTouchUpInside];
//    [_reduceButton addTarget:self action:@selector(temperatureReduce:) forControlEvents:UIControlEventTouchUpInside];
    
    /**底部4个label*/
    _pmLabel = [self setupLabel];
    _tvocLabel = [self setupLabel];
    _roomTemperatureLabel = [self setupLabel];
    _humidityLabel = [self setupLabel];
    
    CGFloat marign = 8;
//    _pmLabel.left = 15;
//    _pmLabel.centerY = (self.bottom - _circleHanderView.bottom ) /2 + _circleHanderView.bottom;
//
//    _tvocLabel.left = _pmLabel.right + marign;
//    _tvocLabel.bottom = _pmLabel.bottom;
//
//    _humidityLabel.left = _tvocLabel.right + marign;
//    _humidityLabel.bottom = _tvocLabel.bottom;
//
//    _roomTemperatureLabel.left = _humidityLabel.right + marign;
//    _roomTemperatureLabel.bottom = _humidityLabel.bottom;
    
    //老板说改成2行
    _pmLabel.left = 15;
    _pmLabel.centerY = (self.bottom - _circleHanderView.bottom ) * 0.25 + _circleHanderView.bottom;
    
    _tvocLabel.right =  _middleView.width - marign;
    _tvocLabel.bottom = _pmLabel.bottom;
    
    _humidityLabel.left = 15;
    _humidityLabel.centerY = (self.bottom - _circleHanderView.bottom ) * 0.75 + _circleHanderView.bottom;
    
    _roomTemperatureLabel.right = _middleView.width - marign;
    _roomTemperatureLabel.bottom = _humidityLabel.bottom;
    
    
    /**
     温度
     */
    _temperatureLabel = [[UILabel alloc] init];
    _temperatureLabel.width = circleSilderHeight /2;
    _temperatureLabel.height = circleSilderHeight /2;
    _temperatureLabel.textAlignment = NSTextAlignmentCenter;
    _temperatureLabel.textColor = kDeviceLabelColor;
    if(ZYiPhone5_OR_5c_OR_5s || ZYiPhone4_OR_4s){
        _temperatureLabel.font = [UIFont systemFontOfSize:68];
    }else if(ZYiPhone6Plus_OR_6sPlus){
        _temperatureLabel.font = [UIFont systemFontOfSize:85];
    }else{
        _temperatureLabel.font = [UIFont systemFontOfSize:82];
    }
    
    [_middleView addSubview:_temperatureLabel];
    _temperatureLabel.centerX = _middleView.width / 2;
    _temperatureLabel.centerY = _circleHanderView.centerY;
    
    /**
     温度符号
     */
    _temperatureSymbolLabel = [[UILabel alloc] init];
    _temperatureSymbolLabel.width = 20;
    _temperatureSymbolLabel.height = 12;
    _temperatureSymbolLabel.textColor = kDeviceLabelColor;
    _temperatureSymbolLabel.textAlignment = NSTextAlignmentLeft;
    _temperatureSymbolLabel.font = [UIFont systemFontOfSize:17];
    _temperatureSymbolLabel.text = @"℃";
    [_middleView addSubview:_temperatureSymbolLabel];
    _temperatureSymbolLabel.top = _temperatureLabel.top + _temperatureLabel.width / 6;
    _temperatureSymbolLabel.left = _temperatureLabel.right - _temperatureLabel.width / 10;
    
    
    _modeSelectView = [[ZYModeSelectView alloc] initWithFrame:CGRectMake(0, 0, _middleView.width * 0.9, 0) deviceType:ZYDeviceTypeAirConditioning];
    [self addSubview:_modeSelectView];
    _modeSelectView.centerX = _middleView.centerX;
    _modeSelectView.top = _modeLabel.bottom;
    _modeSelectView.delegate = self;
    
    _isAlterSelectView = NO;
    [_modeSelectView setupTitle];
    CGFloat realHeight = _modeSelectView.top + _modeSelectView.realHeight;
    if(realHeight > self.height){
        self.height = realHeight;
    }
    [self setUserInteractionEnabled:YES];
    self.backgroundColor = [UIColor clearColor];
}

-(UIButton *)setupButton:(BOOL)isAdd{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image;
    if(isAdd){
        image = [UIImage imageNamed:@"ic_device_item_add"];
    }else{
        image = [UIImage imageNamed:@"ic_device_item_reduce"];
    }
    button.size = image.size;
//    [button setImage:image forState:UIControlStateNormal];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [_middleView addSubview:button];
    return button;
}

-(UILabel *)setupLabel{
    UILabel *label = [[UILabel alloc] init];
    label.width = (_middleView.width - 30) / 2 - 8;
    label.height = 15;
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = kDeviceLabelColor;
    
    [_middleView addSubview:label];
    return label;
}

-(UIView *)setupSidesView{
    UIView *view = [[UIView alloc] init];
    view.size = CGSizeMake(ZYSCREEN_W * 0.05, self.height);
    [view setBackgroundColor:RGBA(255, 255, 255, 0.7)];
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    [self addSubview:view];
    return view;
}

#pragma mark - Event
-(void)doSlectMode{
    [_modeSelectView showOrHidden];
}


/**
 温度增加
 @param button 当前按钮
 */
-(void)temperatureAdd:(UIButton *)button{
    if(super.device.isLock || !super.device.isOpen){
        return;
    }
    CGFloat temperature = [super.device.temperature floatValue];
    if(++temperature > _maxTempure){
        return;
    }
    [self changeTemperature:temperature];
    temperature =  (temperature - _minTempure) / (_maxTempure - _minTempure );
    [_circleHanderView setValue:temperature];
}


/**
 温度减少

 @param button 当前按钮
 */
-(void)temperatureReduce:(UIButton *)button{
    if(super.device.isLock || !super.device.isOpen){
        return;
    }
    CGFloat temperature = [super.device.temperature floatValue];
    if(--temperature < _minTempure){
        return;
    }
    [self changeTemperature:temperature];
    temperature =  (temperature - _minTempure) / (_maxTempure - _minTempure );
    [_circleHanderView setValue:temperature];
}

//-(void)doChageCircleSilder:(ZYCircleSlider *)slider{
//    NSLog(@"newValue:%d",slider.angle);
//    if([super.delegate respondsToSelector:@selector(deviceItemView:changeTemperature:device:)]){
//        [super.delegate deviceItemView:self changeTemperature:slider.angle device:super.device];
//    }
//}


-(void)setDevice:(ZYDevice *)device{
    super.device = device;
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    _pmLabel.text = [NSString stringWithFormat:@"PM2.5：%@%@",device.pmExponent,device.pmQuality];
    _tvocLabel.text = [NSString stringWithFormat:@"TVOC：%@",device.tvoc];
    _humidityLabel.text = [NSString stringWithFormat:@"%@：%@%%",[language getStringByKey:LC_HOME_MAIN_HUMIDITY],device.humidity];
    _roomTemperatureLabel.text = [NSString stringWithFormat:@"%@：%@℃",[language getStringByKey:LC_HOME_MAIN_ROOM_TEMPERATURE],device.roomTemperature];
    if(device.type == ZYDeviceTypeAirConditioning){
        _maxTempure = 30;
        _minTempure = 10;
    }else{
        _maxTempure = 34;
        _minTempure = 5;
    }
    if(device.isConnect){
        _wifiImageView.image = [UIImage imageNamed:@"ic_home_main_wifi"];
    }else{
        _wifiImageView.image = [UIImage imageNamed:@"ic_no_wifi"];
    }
    _temperatureLabel.text = device.temperature;
    CGFloat temperature = [device.temperature floatValue];
//    [_circleHanderView setTempureValue:[device.temperature floatValue]];
    temperature =  (temperature - _minTempure) / (_maxTempure - _minTempure );
    [_circleHanderView setValue:temperature];
    _nameLabel.text = device.name;
    NSDictionary *attributes = @{NSFontAttributeName:_nameLabel.font,};
    CGSize textSize = [device.name boundingRectWithSize:CGSizeMake(_middleView.width * 3 / 4 , _nameLabel.height)
                                                options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    _nameLabel.width = textSize.width;
//    _wifiImageView.left = _nameLabel.right + 3;
    
    NSDictionary *bottomAttributes = @{NSFontAttributeName:_pmLabel.font,};
    CGSize bottomTextSize = [_pmLabel.text boundingRectWithSize:CGSizeMake(_middleView.width / 4 - 15, _pmLabel.height)
                                                options:NSStringDrawingTruncatesLastVisibleLine attributes:bottomAttributes context:nil].size;
    if(bottomTextSize.width > _pmLabel.width){
        _pmLabel.size = bottomTextSize;
        _tvocLabel.left = _pmLabel.right + 8;
        _humidityLabel.left = _tvocLabel.right + 8;
        _roomTemperatureLabel.left = _humidityLabel.right + 8;
    }
    [_modeSelectView setupTitle];
//    [UIView animateWithDuration:0.3 animations:^{
//        [self layoutIfNeeded];
//    }];
    [self selectModeType:device.modeType];
    //判断是否锁定设备
    _modeSelectView.userInteractionEnabled = !super.device.isLock;
    _circleHanderView.enabled = !super.device.isLock;
}

-(void)setIsLock:(BOOL)isLock{
    super.device.isLock = isLock;
    //判断是否锁定设备
    _modeSelectView.userInteractionEnabled = (!isLock && super.device.isOpen);
    _circleHanderView.enabled = (!isLock && super.device.isOpen);
}

-(void)setIsOpen:(BOOL)isOpen{
    super.device.isOpen = isOpen;
    //判断是否锁定设备
    _modeSelectView.userInteractionEnabled = (isOpen && !super.device.isLock);
    _circleHanderView.enabled = (isOpen && !super.device.isLock);
}


-(void)selectModeType:(NSUInteger)modeType{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    switch (modeType) {
        case ZYDeviceModeCustom:
            _modeImageView.image = [UIImage imageNamed:@"ic_home_mode_custom_selected"];
            _modeLabel.text = [language getStringByKey:LC_DEVICE_MODE_TYPE_CUSTOM];
            break;
        case ZYDeviceModeEnergySaving:
            _modeImageView.image = [UIImage imageNamed:@"ic_home_mode_energy_saving_selected"];
            _modeLabel.text = [language getStringByKey:LC_DEVICE_MODE_TYPE_ENERGY_SAVING];
            break;
        case ZYDeviceModeComfortable:
            _modeImageView.image = [UIImage imageNamed:@"ic_home_mode_comfortable_selected"];
            _modeLabel.text = [language getStringByKey:LC_DEVICE_MODE_TYPE_COMFORTABLE];
            break;
        case ZYDeviceModeManual:
            _modeImageView.image = [UIImage imageNamed:@"ic_mode_type_manual_selected"];
            _modeLabel.text = [language getStringByKey:LC_DEVICE_MODE_TYPE_MANUAL];
            break;
        default:
            break;
    }
}

#pragma mark ZYModeSelectViewDelegate
-(void)modeSelectView:(ZYModeSelectView *)modeSelectView setModeType:(NSUInteger)modeType{
    if(super.device.isLock){
        return;
    }
    if(super.device.modeType == modeType){
        return;
    }
    super.device.modeType = modeType;
    [self selectModeType:modeType];
    if([super.delegate respondsToSelector:@selector(deviceItemView:setModeType:device:)]){
        [super.delegate deviceItemView:self setModeType:modeType device:super.device];
    }
}

#pragma mark - ZYCircleHanderViewDelegate
//-(void)circleHanderView:(ZYCircleHanderView *)circleHanderView changeTemperature:(int)temperature{
//    [self changeTemperature:temperature];
//}
//
//-(void)circleHanderView:(ZYCircleHanderView *)circleHanderView isChangeTemperature:(BOOL)isChange{
//    if([super.delegate respondsToSelector:@selector(deviceItemView:isChangeTemperature:)]){
//        [super.delegate deviceItemView:self isChangeTemperature:isChange];
//    }
//}
- (void)circleSliderValueDidChanged:(ZCircleSlider *)slider {
    if (!slider.interaction) {
        return;
    }
    CGFloat temperature = (_maxTempure - _minTempure) * slider.value + _minTempure;
    [self changeTemperature:temperature];
}

- (void)circleSliderValueChanging:(ZCircleSlider *)slider {
    if (!slider.interaction) {
        return;
    }
    if([super.delegate respondsToSelector:@selector(deviceItemView:isChangeTemperature:)]){
        [super.delegate deviceItemView:self isChangeTemperature:YES];
    }
}

- (void)circleSliderTouchDown:(ZCircleSlider *)slider {
    if (!slider.interaction) {
        return;
    }
    if([super.delegate respondsToSelector:@selector(deviceItemView:isChangeTemperature:)]){
        [super.delegate deviceItemView:self isChangeTemperature:NO];
    }
}

#pragma mark - private
//温度改变
-(void)changeTemperature:(CGFloat)temperature{
//    temperature = floor(temperature);
    _temperatureLabel.text = [NSString stringWithFormat:@"%.0f",temperature];
    super.device.temperature = [NSString stringWithFormat:@"%.0f",temperature];
    if([super.delegate respondsToSelector:@selector(deviceItemView:changeTemperature:device:)]){
        [super.delegate deviceItemView:self changeTemperature:temperature device:super.device];
    }
}

#pragma mark - public
-(void)setScrollStatus:(BOOL)isScroll{
//    [UIView animateWithDuration:0.3 animations:^{
//        [_leftView setHidden:isScroll];
//        [_rightView setHidden:isScroll];
//    }];
    [_modeImageView setUserInteractionEnabled:!isScroll];
    [_circleHanderView setEnabled:!isScroll];
}

@end
